package com.example.ll_video.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;


import androidx.core.app.ActivityCompat;

import com.bun.miitmdid.core.ErrorCode;
import com.bun.miitmdid.core.IIdentifierListener;
import com.bun.miitmdid.core.MdidSdkHelper;
import com.bun.miitmdid.supplier.IdSupplier;
import com.example.ll_video.MyApplication;

import java.net.NetworkInterface;
import java.util.Collections;
import java.util.List;
import java.util.Objects;


import static android.content.Context.TELEPHONY_SERVICE;

/**
 * Description:
 * Company    : xi'an yikang
 * Author     : Daluzy
 * Date       : 2019/1/8 11:24
 */
public class DevicesUtil {
    /**
     * 获取手机唯一标识 SerialNumber
     *
     * @return SerialNumber
     */
    @SuppressLint("HardwareIds")
    public static String getSerialNumber(Context context) {

        try {
            StringBuffer stringBuffer = new StringBuffer(Build.DEVICE);
            stringBuffer.append(Build.PRODUCT);
            stringBuffer.append(Build.SERIAL);
            stringBuffer.append(Build.USER);
            stringBuffer.append(Build.MANUFACTURER);
            stringBuffer.append(Build.MODEL);
            stringBuffer.append(Build.BRAND);
            stringBuffer.append(Build.TYPE);

            String divicesId = MD5.getStringMD5(stringBuffer.toString());
            Log.i("qin>>>", String.valueOf(divicesId));

            String str5 = null;
            if (PhoneRealyOrNo.notHasLightSensorManager(context)) {
                return "moniqi";
            }
            String SerialNumber = "";
            TelephonyManager TelephonyMgr = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                SerialNumber = Build.SERIAL;
                if (SerialNumber != null && SerialNumber.length() > 0)
                    return SerialNumber;
            }
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                str5 = Build.getSerial();
            }
            SerialNumber = Objects.requireNonNull(TelephonyMgr).getDeviceId();
            if (SerialNumber != null) {
                if (SerialNumber.length() < 1) {
                    SerialNumber = Objects.requireNonNull(TelephonyMgr).getSimSerialNumber();
                }
            } else {
                SerialNumber = Objects.requireNonNull(TelephonyMgr).getSimSerialNumber();
            }
            if (SerialNumber != null) {
                if (SerialNumber.length() < 1) {
                    SerialNumber = str5;
                }
            } else {
                SerialNumber = str5;
            }
            if (SerialNumber != null) {
                if (SerialNumber.length() < 1) {
                    SerialNumber = Build.SERIAL;
                }
            } else {
                SerialNumber = Build.SERIAL;
            }
            if (SerialNumber != null && SerialNumber.length() > 0 && !(SerialNumber.contains("unknown"))) {
                return SerialNumber;
            } else {
                if (divicesId != null && !divicesId.isEmpty() && !divicesId.contains("null")) {
                    return divicesId;
                } else {
                    return  getOaid(context);
                }
            }
        } catch (Exception e) {
            return  getOaid(context);
        }

    }

    private static final String TAG = "DevicesUtil";

    private static final String TEMP_DIR = "system_config";
    private static final String TEMP_FILE_NAME = "system_file";
    private static final String TEMP_FILE_NAME_MIME_TYPE = "application/octet-stream";
    private static final String SP_NAME = "device_info";
    private static final String SP_KEY_DEVICE_ID = "device_id";

    public static String getDeviceId(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        String deviceId = sharedPreferences.getString(SP_KEY_DEVICE_ID, null);
        if (!TextUtils.isEmpty(deviceId)) {
            return deviceId;
        }
//        deviceId = getIMEI(context);
        if (TextUtils.isEmpty(deviceId)) {
            deviceId = createUUID(context);
        }
        sharedPreferences.edit()
                .putString(SP_KEY_DEVICE_ID, deviceId)
                .apply();
        return deviceId;
    }

    public static String createUUID(Context context) {
        final String[] uuid = new String[1];
        /*if (getMacAddress() != null && !getMacAddress().isEmpty()){
            uuid[0] = getMacAddress();
            return uuid[0];
        }else {*/

        return uuid[0];
//        }
    }


    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取手机产品名称
     *
     * @return 手机产品名称
     */
    public static String getDeviceProduct() {
        return android.os.Build.PRODUCT;
    }

    /**
     * 获取手机设备名
     *
     * @return 手机设备名
     */
    public static String getDeviceName() {
        return android.os.Build.DEVICE;
    }

    public static String getNum() {
        int first = Integer.parseInt("10010110", 2);
        int second = Integer.parseInt("101110110111", 2);
        int third = Integer.parseInt("101111100011", 2);
        return String.format("%s%s%s", first, second, third);
    }

    /**
     * 获取IMEI码
     *
     * @param context
     * @return
     */
    @SuppressLint("MissingPermission")
    public static String getIMEI(Context context) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return tm.getImei();
        } else {
            return tm.getDeviceId();
        }
    }

    /**
     * 获取设备序列号
     *
     * @return
     */
    @SuppressLint("MissingPermission")
    public static String getSerial() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return Build.getSerial();
        } else {
            return Build.SERIAL;
        }
    }

    /**
     * 获取Mac地址
     * android 6/7 会有问题和异常
     * 目前9和10 还算正常
     */
    public static String getMacAddress() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) {
                    continue;
                }
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }
                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取ANDROID_ID
     * ANDROID_ID的获取不需要任何权限，并且可以很好地保证唯一性，缺点就是无法保证稳定性，即一些操作可能导致ANDROID_ID的改变
     *
     * @param context
     * @return
     */
    public static String getAndroidId(Context context) {
        return Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }


    /**
     * 获取唯一标识idfa
     *
     * @return
     */
    /**
     * 获取Oaid
     *
     * @return oaid或错误码
     */
    public static String getOaid(Context context) {
        String idfa;
        if (MyApplication.isSupportOaid()) {
            idfa = MyApplication.getOaid();
        } else {
            idfa = getAndroidId(context);
        }
        return idfa;
    }

    /**
     * 获取补充设备标识
     *
     * @param context
     * @param listener
     */
    public static void getSupplierDeviceId(Context context, final OnSupplierDeviceIdListener listener) {
        int result = MdidSdkHelper.InitSdk(context, true, new IIdentifierListener() {
            @Override
            public void OnSupport(boolean isSupport, IdSupplier idSupplier) {
                if (isSupport) {
                    listener.onSuccess(idSupplier);
                }
                // 释放连接
                idSupplier.shutDown();
            }
        });
        switch (result) {
            case ErrorCode.INIT_ERROR_MANUFACTURER_NOSUPPORT:
                // 不支持的设备厂商
                listener.onFailed("不支持的设备厂商");
                break;
            case ErrorCode.INIT_ERROR_DEVICE_NOSUPPORT:
                listener.onFailed("不支持的设备");
                break;
            case ErrorCode.INIT_ERROR_LOAD_CONFIGFILE:
                listener.onFailed("加载配置文件出错");
                break;
            case ErrorCode.INIT_ERROR_RESULT_DELAY:
                // 获取接口是异步的，结果会在回调中返回，回调执行的回调可能在工作线程
                break;
            case ErrorCode.INIT_HELPER_CALL_ERROR:
                listener.onFailed("反射调用出错");
                break;
            default:
                break;
        }
    }

    /**
     * 获取设备标识
     *
     * @param context
     * @param listener
     */
    public static void getDeviceId(final Context context, final OnDeviceIdListener listener) {
        MdidSdkHelper.InitSdk(context, true, new IIdentifierListener() {
            @Override
            public void OnSupport(boolean isSupport, IdSupplier idSupplier) {
                String deviceId;
                if (isSupport) {
                    // 支持获取补充设备标识
                    deviceId = idSupplier.getOAID();
                } else {
                    // 不支持获取补充设备标识
                    // 可以自己决定设备标识获取方案，这里直接使用了ANDROID_ID
                    deviceId = getAndroidId(context);
                }
                // 将设备标识MD5加密后返回，以获取统一格式
                listener.onSuccess(MD5.getStringMD5(deviceId));
                // 释放连接
                idSupplier.shutDown();
            }
        });
    }

    /**
     * 获取补充设备标识回调
     */
    public interface OnSupplierDeviceIdListener {
        /**
         * 获取补充设备标识成功
         *
         * @param idSupplier
         */
        void onSuccess(IdSupplier idSupplier);

        /**
         * 获取补充设备标识失败
         *
         * @param message 失败原因
         */
        void onFailed(String message);
    }

    /**
     * 获取设备标识回调
     */
    public interface OnDeviceIdListener {
        /**
         * 获取设备标识成功
         */
        void onSuccess(String deviceId);

        void onError();
    }
}
